<?php
/**
 * Created by PhpStorm.
 * User: winleung
 * Date: 2019-10-22
 * Time: 18:22
 */

namespace app\api\controller;


use app\api\service\OrderService;
use app\api\service\PharmacyOrderService;
use app\api\service\ProductService;
use app\api\service\WechatInfoService;
use GuzzleHttp\Client;
use think\Controller;
use think\Log;
use think\Request;
use app\api\service\PharmacyService;

class Pharmacy extends Controller
{

    private $pharmacyService;

    private $orderService;

    private $ps;

    private $productService;

    private $pharmacyOrderService;

    private $wechatInfoService;

    public function __construct(Request $request, PharmacyService $pharmacyService,  OrderService $orderService, ProductService $productService, WechatInfoService $wechatInfoService)
    {
        parent::__construct($request);

        $this->pharmacyService = $pharmacyService;

        $this->orderService = $orderService;

        $this->ps    = $pharmacyService;

        $this->productService = $productService;

        $this->pharmacyOrderService = new PharmacyOrderService();

        $this->wechatInfoService = $wechatInfoService;
    }

    /**
     * 商户初始化注册
     * @return \think\response\Json
     */
    public function postRegister()
    {
        $validateResult = $this->validate($this->request->post(), 'Pharmacy.register');
        if ($validateResult !== true) {
            throwBusinessException($validateResult);
        }

        $result = $this->pharmacyService->registerPharmacyAccount($this->request->post());
        return jsonResult($result);
    }



    /**
     * 更新审核状态
     * @return \think\response\Json
     */
    public function putUpdatePharmacyStatus()
    {
        $validateResult = $this->validate($this->request->put(), 'Pharmacy.putUpdatePharmacyStatus');
        if ($validateResult !== true) {
            throwBusinessException($validateResult);
        }

        $result = $this->pharmacyService->updatePharmacyStatus($this->request->post());

        return jsonResult($result);
    }

    /**
     * 查询店铺详情
     * @return \think\response\Json
     */
    public function getPharmacyInfo()
    {
        $validateResult = $this->validate($this->request->get(), 'Pharmacy.getPharmacyInfo');
        if ($validateResult !== true) {
            throwBusinessException($validateResult);
        }

        $result = $this->pharmacyService->getPharmacyInfo($this->request->get("pharmacy_id"));

        return jsonResult($result);
    }


    /**
     * 查询订单的详情
     */
    public function getOrderDetail(){

        $orderId = $this->request->param('order_id');

        if(empty($orderId) || $orderId == 0){
            throwBusinessException('order_id不能为空');
        }

        $data = $this->getOrderDetailPrivate($orderId);

        return jsonResult($data);
    }

    private function getOrderDetailPrivate($orderId){

        $data = $this->orderService->fetchOrderDetail($orderId);

        $data = $data[0];

        if(!empty($data)){
            $product = $this->productService->fetchOrderProduct($orderId);

            $data['product_detail'] = $product;

            $getProductNo = $this->pharmacyOrderService->fetchPharmacyOrderInfoByOrder($orderId);

            $getProductNo = $getProductNo[0]['id'];

            $data['get_product_no']  = $getProductNo;
        }else{

            throw new \Exception("没有查询到该订单");
        }

        return $data;

    }


    /**
     * 查询药店待接收的订单
     */
    public function getToAcceptOrder(){
        $pharmacyId = $this->request->param('pharmacy_id');

        if(empty($pharmacyId) || $pharmacyId == 0){
            throwBusinessException('pharmacy_id不能为空');
        }

        $data = $this->ps->fetchToAcceptOrder($pharmacyId);

        if(!empty($data)){

            $result = [];

            foreach ($data as $key=>$va){
                try{

                    $d1 = $this->getOrderDetailPrivate($va['order_id']);

                    array_push($result, $d1);

                }catch (\Exception $e){
                    Log::error($e->getMessage());
                }

            }
        }else{
            //没有待处理接受的订单
            return jsonResult([]);
        }

        return jsonResult($result);
    }


    /**
     * 获取已接收的订单，需要去完成拣货的订单
     * @return \think\response\Json
     */
    public function getToDonePickingOrder(){

        $pharmacyId = $this->request->param('pharmacy_id');

        if(empty($pharmacyId) || $pharmacyId == 0){
            throwBusinessException('pharmacy_id不能为空');
        }

        $data = $this->ps->getPharmacyOrderToPickings($pharmacyId);

        if(!empty($data)){

            $result = [];

            foreach ($data as $key=>$va){
                try{

                    $d1 = $this->getOrderDetailPrivate($va['order_id']);

                    array_push($result, $d1);

                }catch (\Exception $e){
                    Log::error($e->getMessage());
                }

            }
        }else{
            //没有待处理接受的订单
            return jsonResult([]);
        }

        return jsonResult($result);

    }

    /**
     * 药店拣货
     * @return \think\response\Json
     */
    public function postOrderStatusToPicking(){
        $pharmacyId = $this->request->param('pharmacy_id');
        $orderId = $this->request->param('order_id');

        try{
            $result = $this->ps->pickingOrder($pharmacyId, $orderId);

            if($result){
                return jsonResult([], '操作成功！');
            }else{
                return jsonResult([], '没有可更新的数据');
            }

        }catch (\Exception $e){
            throwBusinessException($e->getMessage());
        }

    }

    /**
     * 更新订单的状态为拣货完成
     * @return \think\response\Json
     */
    public function postOrderStatusToDonePicking()
    {
        $pharmacyId = $this->request->param('pharmacy_id');
        $orderId = $this->request->param('order_id');
        $imageUrl = $this->request->param('image_url');

        if(empty($pharmacyId) || $pharmacyId == 0 || empty($orderId) || empty($imageUrl)){
            throwBusinessException('pharmacy_id不能为空 或者 订单id不能为空 或者图片地址不能为空');
        }

        $result = $this->pharmacyOrderService->updatePharmacyOrderStatus($this->request, ['status'=>3, 'order_id'=>$orderId], $imageUrl);

        if ($result) {
            return jsonResult([], '操作成功！');
        }else{
            return jsonResult([], '更新失败！', 200, [],  [], $status = 300);
        }

    }


    /**
     * 上传文件
     * @return \think\response\Json
     * @throws \Exception
     */
    public function postUploadFile(){

        $file = \request()->file('image');

        if($file) {

            $dir = '/jiayouernv/www/upload';
            //ROOT_PATH . 'public/uploads'
            $result = $file->move($dir);

            if(!$result){
                throw new \Exception($file->getError());
            }

            $fileUrl = 'upload'.DS.$result->getSaveName();

            return jsonResult(['file_path'=>$fileUrl], '上传成功');

        }else{
            throw new \Exception("上传文件失败！");
        }
    }

    /**
     * 药店登录
     * @return \think\response\Json
     */
    public function postLogin(){
        Log::info("传入的code");
        $mobilephone = $this->request->param('mobilephone');
        $password = $this->request->param('password');
        $code = $this->request->param('code');

        try{
            $data = $this->pharmacyService->login($mobilephone, $password, $code);
            return jsonResult($data);
        }catch (\Exception $e){
            throwBusinessException($e->getMessage());
        }

    }


    /**
     * 用户通过code 登录
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserIdByCodeOpenid(){

        $code = $this->request->param('code');

        if(empty($code)){
            Log::error('接收到的code为空');

            return jsonResult([], '接收到的code问空');
        }

        $wechatInfo = new WechatInfoService();
        $appId =\config('wechat.appid');
        $openid = $wechatInfo->getWechatOpenId($appId, $code);

        $userInfo = $this->pharmacyService->getUserInfoByOpenid($openid);

        return jsonResult($userInfo);


    }

    /**
     * 获取微信的accesstoken
     */
    public function getAccessToken(){

        $appId = \config('wechat.appid');

        $token = $this->wechatInfoService->getAccessTokenIncludeJs($appId);
        unset($token['secret']);
        return jsonResult($token);

    }


    /**
     *
     * 获取已完成的订单
     *
     * @return \think\response\Json
     */
    public function getHasDoneOrder(){

        $pharmacyId = $this->request->param('pharmacy_id');

        if(empty($pharmacyId) || $pharmacyId == 0){
            throwBusinessException('pharmacy_id不能为空');
        }

        $data = $this->ps->fetchHasDoneOrder($pharmacyId);

        if(!empty($data)){

            $result = [];

            foreach ($data as $key=>$va){
                try{

                    $d1 = $this->getOrderDetailPrivate($va['order_id']);

                    array_push($result, $d1);

                }catch (\Exception $e){
                    Log::error($e->getMessage());
                }

            }
        }else{
            //没有待处理接受的订单
            return jsonResult([]);
        }

        return jsonResult($result);

    }


}